package cn.xiyue.production.base;

import java.lang.reflect.Field;

import cn.xiyue.production.network.HttpRequest;
import cn.xiyue.production.network.RequestApi;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CallableActivity extends BaseActivity {
    protected static RequestApi requestApi;

    static {
        requestApi = HttpRequest.getRequestApi();
    }

    protected <T> void async(Call<T> call, Callable<T> callable) {
        async(call, callable, true);
    }

    protected <T> void async(Call<T> call, Callable<T> callable, boolean showDialog) {

        if (showDialog) showDialog();

        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                T body = response.body();

                try {
                    Field code = body.getClass().getDeclaredField("status");
                    code.setAccessible(true);
                    int anInt = code.getInt(body);
                    switch (anInt) {
                        case 200:
                            callable.call(body);
                            break;
                        case 400:
                            showToast("请求失败");
                            break;
                        case 401:
                            showToast("权限不足");
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (showDialog) closeDialog();
            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {
                showToast("请求失败，请检查你的网络重试！");
                t.printStackTrace();
                if (showDialog) closeDialog();
            }
        });
    }

    public interface Callable<T> {
        void call(T value);
    }
}
